<script setup>
import useWebSocket from "@/utils/websocket.js";
import {computed, nextTick, onMounted, ref, watch} from "vue";
import useUserInfoStore from "@/store/user.js";
import {AddFriend, friendRequestStatus, getUserDetail, ViewChatHistory} from "@/api/index.js";
import {ElMessage} from "element-plus";
import UserTooltipCard from "@/components/UserTooltipCard.vue";

const userStore = useUserInfoStore();

const token = userStore.userInfo['token'];

const username = userStore.userInfo['username']
const {
  onlineUsersData: onlineUsers,
  messagesData: messages,
  sendMessage,
} = useWebSocket(`ws://47.108.82.9:9001/ws/chat/room1/?token=${token}`)

// 本地消息输入
const newMessage = ref('');

const handleSendMessage = () => {
  const trimmedMessage = newMessage.value.trim();

  if (trimmedMessage) {
    const sendData = {
      sender: userStore.userInfo.username,
      text: trimmedMessage,
      token: token
    };
    // 通过 WebSocket 发送消息
    sendMessage(JSON.stringify({message: sendData}));
    canViewHistory.value = false
    newMessage.value = '';
  }
};
const isMyMessage = (name) => {
  return name === username
}
const messagesContainer = ref(null); // 创建对消息容器的引用
// 监视消息变化以自动滚动
const isScrollable = ref(false);
watch(messages, () => {
  nextTick(() => {
    const content = messagesContainer.value;
    content.scrollTo({top: content.scrollHeight, behavior: "smooth"});
    isScrollable.value = content.scrollHeight > content.clientHeight;
  });
}, {
  deep: true,
});

const handleBackToTop = () => {
  const content = messagesContainer.value;
  content.scrollTo({top: 0, behavior: "smooth"});
}


const canViewHistory = ref(true);
let historyMeg = ref([])
const handleViewChatHistory = async (room) => {
  try {
    const res = await ViewChatHistory(room);
    historyMeg.value = res
    canViewHistory.value = false
  } catch (error) {
    console.log(error)
  }
};

//合并历史消息和新发送的消息
const allMessages = computed(() => [...historyMeg.value, ...messages.value]);

const handleAddFriend = async (friendId) => {
  try {
    friendStatuses.value[friendId] = true;
    await AddFriend(friendId)
    ElMessage.success('添加好友成功，请等待好友同意')
  } catch (error) {
    ElMessage.warning('好友请求已发送。请等待好友处理')
  }
};
const friendStatuses = ref({});

onMounted(async () => {
  watch(onlineUsers, async (newUsers) => {
    if (newUsers.length > 0) {
      for (let friend of newUsers) {
        try {
          console.log(`check${friend.id}`)
          const res = await friendRequestStatus(friend.id);
          friendStatuses.value[friend.id] = res.status;
          await fetchTooltipContent(friend.id);
          console.log(`status${friendStatuses.value[friend.id]}`)
        } catch (error) {
          console.error(`Error fetching status for friend ID ${friend.id}:`, error);
        }
      }
    } else {
      console.log('No online users found.');
    }
  });
});
const tooltipContents = ref({});

const fetchTooltipContent = async (friendId) => {
  console.log(`正在获取 ${friendId} 的工具提示`); // 调试日志
  if (!tooltipContents.value[friendId]) {
    try {
      const response = await getUserDetail(friendId);
      console.log(response);
      tooltipContents.value[friendId] = response;
      console.log(tooltipContents.value[friendId]);
    } catch (error) {
      console.error('Error fetching tooltip content:', error);
      tooltipContents.value[friendId] = 'Error loading content';
    }
  }
};

</script>

<template>
  <div class="chat-panel">
    <div class="chat-content">
      <el-button @click="handleViewChatHistory('room1')" v-show="canViewHistory">查看历史消息</el-button>
      <div class="messages" ref="messagesContainer">
        <div v-for="(msg, index) in allMessages" :key="index" class="message"
             :class="{ 'my-message': isMyMessage(msg.username) }">
          <el-avatar
              v-if="!isMyMessage(msg.username)"
              :size="45"
              :src="msg.avatar ? '/aps/' + msg.avatar : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
          ></el-avatar>
          <div class="message-content">
            <strong class="sender" v-if="!isMyMessage(msg.message.token)">{{ msg.username }}</strong>
            <span class="text">{{ msg.message.text }}</span>
          </div>
          <el-avatar
              v-if="isMyMessage(msg.username)"
              :size="45"
              :src="msg.avatar ? '/aps/' + msg.avatar : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
          ></el-avatar>
        </div>
      </div>
      <div class="message-input">
        <input v-model="newMessage" @keyup.enter="handleSendMessage" placeholder="输入消息..."/>
        <el-button @click="handleSendMessage">发送</el-button>
      </div>
    </div>
    <div class="online-friends">
      <h3>在线朋友</h3>
      <el-card v-for="(friend, index) in onlineUsers" :key="index" class="friend-card"
               v-show="!isMyMessage(friend.username)">
        <div class="friend-content">
          <el-tooltip
              class="box-item"
              effect="light"
              placement="left"
              trigger="hover"
          >
            <template #content>
              <UserTooltipCard :userDetail="tooltipContents[friend.id] || {}"/>
            </template>
            <el-avatar
                :src="friend.avatar ? '/aps/' + friend.avatar : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
                :size="40" class="avatar"></el-avatar>
          </el-tooltip>
          <span class="friend-name">{{ friend.username }}</span>
          <el-button
              v-if="friendStatuses[friend.id] === 'not_found'||friendStatuses[friend.id]==='rejected'"
              @click="handleAddFriend(friend.id)"
              type="success"
              size="small"
              class="add-friend-button">
            +
          </el-button>
        </div>
      </el-card>
      <el-button @click="handleBackToTop">回到顶部</el-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.chat-panel {
  display: flex;
  height: 100%;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 10px;
  border-right: 1px solid #ccc;
}

.messages {
  flex: 1;
  overflow: auto;
}

.message {
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.message-content {
  display: flex;
  flex-direction: column;
}

.my-message {
  justify-content: flex-end; /* 自己的消息显示在右边 */
  text-align: right; /* 让内容对齐 */
}

.message-input {
  display: flex;
  margin-top: 10px;
}

.message-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.message-input button {
  padding: 8px 12px;
  margin-left: 5px;
}

.online-friends {
  width: 280px;
  padding: 10px;
  border-left: 1px solid #ccc;
  display: flex;
  flex-direction: column;
}

.online-friends h3 {
  margin-top: 0;
}

.friend-content {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使内容分散对齐 */
}

.add-friend-button {
  margin-left: 10px; /* 增加按钮与好友名称之间的间距 */
}

.sender {
  font-size: 0.05em; /* 调整发送者字体大小 */
  margin-bottom: 2px; /* 增加底部间距 */
  transition: color 0.3s; /* 添加颜色变化特效 */
}

.text {
  position: relative; /* 设置相对定位 */
  font-size: 0.9em; /* 调整消息内容字体大小 */
  padding: 10px; /* 添加内边距 */
  border-radius: 8px; /* 圆角效果 */
  background: linear-gradient(135deg, #e0f7fa, #80deea); /* 渐变背景 */
  border: 1px solid #009688; /* 边框颜色 */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* 更明显的阴影效果 */
  transition: background-color 0.3s, transform 0.3s; /* 添加背景和缩放的特效 */
}

.text::after {
  content: '';
  position: absolute;
  bottom: 100%; /* 指向发送者的角 */
  left: 10px; /* 调整指向的横向位置 */
  border-width: 6px;
  border-style: solid;
  border-color: transparent transparent #e0f7fa transparent; /* 云朵角的颜色 */
}

.text:hover {
  background: linear-gradient(135deg, #80deea, #26c6da); /* 悬停时渐变颜色 */
  transform: scale(1.02); /* 悬停时放大效果 */
}


.message:hover .sender {
  color: #007bff; /* 鼠标悬停时发送者颜色 */
}

.message:hover .text {
  background-color: #f0f0f0; /* 鼠标悬停时背景颜色 */
}
</style>